<?php

/**
 * File Name：Menu.php
 * File Encoding：UTF-8
 * File New Time：2014-5-4 8:58:30
 * Author：水平凡
 * Mailbox：admin@abc3210.com
 */
class Menu extends BaseModel {

    public function init()
    {
        parent::init();
        Tree::$Field = 'parentid';
    }

    public function tableName() {
        return '{{admin_menu}}';
    }

    public function rules() {
        return array(
            array('name', 'required', 'message' => '请填写菜单名称！'),
            array('app', 'required', 'message' => '请填写模块名称！'),
            array('controller', 'required', 'message' => '请填写控制器名称！'),
            array('action', 'required', 'message' => '请填写方法名称！'),
            //安全的。。。
            array('name,parentid,app,controller,action,parameter,type,status,remark,listorder', 'safe'),
        );
    }

    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    /**
     * 获取菜单导航
     * @param type $app
     * @param type $model
     * @param type $action
     */
    public function getMenu() {
        $menuid = (int) $_GET['menuid'];
        $cookie = Yii::app()->request->getCookies();
        $menuid = $menuid ? $menuid : $cookie['menuid']->value;
        $model = $this->findAll($this->where(array(
                    'id' => $menuid,
                    'order' => 'listorder desc',
        )));
        if (empty($model)) {
            return array();
        }
        //当前菜单信息
        $info = array();
        foreach ($model as $obj) {
            $info[$obj->id] = $obj->attributes;
        }
        //查询子菜单
        $modeld = $this->findAll($this->where(array(
                    "parentid" => $menuid,
                    "status" => 1,
                    'order' => 'listorder desc',
        )));
        if ($modeld) {
            $find = array();
            foreach ($modeld as $obj) {
                $find[$obj->id] = $obj->attributes;
            }
            if ($find) {
                array_unshift($find, $info[$menuid]);
            } else {
                $find = $info;
            }
        } else {
            $find = $info;
        }
        foreach ($find as $k => $v) {
            $find[$k]['parameter'] = "menuid={$menuid}&{$find[$k]['parameter']}";
        }
        return $find;
    }

    /**
     * 获取菜单
     * @return type
     */
    public function getMenuList() {
        $items['0changyong'] = array(
            "id" => "",
            "name" => "常用菜单",
            "parent" => "changyong",
            "url" => AdminBase::U("menu/public_changyong"),
        );
        foreach (AdminPanel::model()->getPanelList(AdminBase::$uid) as $r) {
            $items[$r['menuid'] . '0changyong'] = array(
                "icon" => "",
                "id" => $r['menuid'] . '0changyong',
                "name" => $r['name'],
                "parent" => "changyong",
                "url" => AdminBase::U($r['url']),
            );
        }
        $changyong = array(
            "changyong" => array(
                "icon" => "",
                "id" => "changyong",
                "name" => "常用",
                "parent" => "",
                "url" => "",
                "items" => $items
            )
        );
        $data = $this->getTree(0);
        return array_merge($changyong, $data);
    }

    /**
     * 按父ID查找菜单子项
     * @param integer $parentid   父菜单ID  
     * @param integer $with_self  是否包括他自己
     */
    public function adminMenu($parentid, $with_self = false) {
        //父节点ID
        $parentid = (int) $parentid;
        $model = $this->findAll($this->where(array('parentid' => $parentid, 'status' => 1, 'order' => 'listorder desc,id ASC')));
        if (empty($model)) {
            $result = array();
        } else {
            foreach ($model as $obj) {
                $result[] = $obj->attributes;
            }
        }
        if ($with_self) {
            $withModel = $this->findByPk($parentid);
            $result2[] = $withModel ? $withModel->attributes : array();
            $result = array_merge($result2, $result);
        }
        //是否超级管理员
        if (Yii::app()->passport->isAdministrator()) {
            //如果角色为 1 直接通过
            return $result;
        }
        $array = array();
        foreach ($result as $v) {
            //方法
            $action = $v['action'];
            //条件
            $where = array('app' => $v['app'], 'controller' => $v['controller'], 'action' => $action, 'role_id' => Yii::app()->passport->roleid);
            //如果是菜单项
            if ($v['type'] == 0) {
                $v['controller'] .= $v['id'];
                $action .= $v['id'];
            }
            //public开头的通过
            if (preg_match('/^public_/', $action)) {
                $array[] = $v;
            } else {
                if (preg_match('/^ajax_([a-z]+)_/', $action, $_match)){
                    $action = $_match[1];
                }
                //是否有权限
                if (Access::model()->isCompetence(Yii::app()->passport->roleid, $v['app'],$v['controller'],$action)){
                    $array[] = $v;
                }
            }
        }
        return $array;
    }

    /**
     * 取得树形结构的菜单
     * @param type $myid
     * @param type $parent
     * @param type $Level
     * @return type
     */
    public function getTree($myid, $parent = "", $Level = 1) {
        $data = $this->adminMenu($myid);
        $Level++;
        $ret = array();
        if (is_array($data)) {
            foreach ($data as $a) {
                $id = $a['id'];
                $name = $a['app'];
                $controller = $a['controller'];
                $action = $a['action'];
                //附带参数
                $fu = array("menuid" => $id);
                if (isset($a['parameter'])) {
                    //$fu = "?" . $a['parameter'];暂时不支持
                }
                $array = array(
                    "icon" => "",
                    "id" => $id . $name,
                    "name" => $a['name'],
                    "parent" => $parent,
                    "url" => AdminBase::U("{$name}/{$controller}/{$action}", $fu),
                );
                $ret[$id . $name] = $array;
                $child = $this->getTree($a['id'], $id, $Level);
                //由于后台管理界面只支持三层，超出的不层级的不显示
                if ($child && $Level <= 3) {
                    $ret[$id . $name]['items'] = $child;
                }
            }
        }
        return $ret;
    }

    /**
     * 获取全部菜单
     * @param type $newCache 是否清除缓存
     * @return boolean
     */
    public function getList($newCache = false) {
        //缓存key
        $key = "getListMenu";
        //清理缓存
        if ($newCache) {
            Yii::app()->cache->delete($key);
            return true;
        }
        //读取缓存
        $cache = Yii::app()->cache->get($key);
        if (empty($cache)) {
            $data = $this->findAll(array('order' => 'listorder desc'));
            if (empty($data)) {
                return false;
            }
            $cache = array();
            foreach ($data as $rs) {
                $cache[$rs->id] = $rs->attributes;
            }
            //缓存
            Yii::app()->cache->set($key, $cache);
        }
        return $cache;
    }

    /**
     * 数据保存前操作
     */
    protected function beforeSave() {/*
        $this->app = strtolower($this->app);
        $this->controller = strtolower($this->controller);
        $this->action = strtolower($this->action);*/
        //清除缓存
        $this->getList(true);
        return true;
    }

}
